package com.zys.http.processor.basic;

import cn.hutool.json.JSONUtil;
import com.intellij.openapi.project.Project;
import com.zys.http.constant.HttpEnum;
import com.zys.http.entity.param.ParamProperty;
import jdk.jfr.Description;

import java.util.*;

/**
 * @author zys
 * @since 2025-01-13
 */
public interface TypeValueProcessor {

    @Description("@JsonProperty 全限名")
    String JSON_PROPERTY_ANNO_FQN = "com.fasterxml.jackson.annotation.JsonProperty";

    List<Object> EMPTY_ARRAY = Collections.emptyList();

    String REQUEST_TYPE_KEY = "com.zys.ApiToolRequestType";

    static Map<String, ParamProperty> getDefaultParameterMap() {
        Map<String, ParamProperty> map = new HashMap<>();
        map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
        return map;
    }

    /**
     * 获取类型的默认值
     *
     * @param project /
     * @param type    PsiType/KtParameter
     * @return /
     */
    Object typeDefaultValue(Cloneable type, Project project);

    default void typeParseResult(String parameterName, Object paramDefaultTypeValue, boolean isJson, boolean isJsonPretty, Map<String, ParamProperty> map, HttpEnum.ParamUsage paramUsage) {
        if (isJson) {
            Object value = paramDefaultTypeValue;
            map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_JSON, HttpEnum.ParamUsage.HEADER));
            if (paramDefaultTypeValue instanceof Map<?, ?> || paramDefaultTypeValue instanceof Collection<?> || paramDefaultTypeValue instanceof Object[]) {
                value = isJsonPretty ? JSONUtil.toJsonPrettyStr(paramDefaultTypeValue) : JSONUtil.toJsonStr(paramDefaultTypeValue);
            }
            map.put(parameterName, new ParamProperty(value, HttpEnum.ParamUsage.BODY));
        } else {
            map.put(REQUEST_TYPE_KEY, new ParamProperty(HttpEnum.ContentType.APPLICATION_X_FORM_URLENCODED, HttpEnum.ParamUsage.HEADER));
            if (paramDefaultTypeValue instanceof Map<?, ?> paramMap) {
                paramMap.forEach((k, v) -> map.put(k.toString(), new ParamProperty(v, HttpEnum.ParamUsage.URL)));
            } else {
                map.put(parameterName, new ParamProperty(paramDefaultTypeValue, paramUsage));
            }
        }
    }
}
